<template>
  <div class="row items-center justify-between bg-white relative-position" style="border-radius: 6px">
    <div class="col-4">
      <content-box title="停机占比统计" style="height: 363px">
        <div class="chart full-height full-width" ref="workingTime" id="workingTime"/>
      </content-box>
    </div>
    <div class="padding-l-24 col-8" style="padding-left: 24px">
      <content-box title="停机原因排行" style="height: 363px">
        <div class="chart full-width" style="height: 287px" ref="chart" id="chart"/>
      </content-box>
    </div>
    <q-inner-loading :showing="loading" style="z-index: 99">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </div>
</template>

<script>
import contentBox from 'src/pages/status-monitor-v3/components/status-overview/content-box'
import { addListener } from 'resize-detector'
import echarts from 'echarts'
import chart from 'src/pages/status-monitor-v3/components/status-overview/chart-option'
import { getShifts, getShiftsDate } from 'src/boot/home/home-new'
import { getStopChart } from 'src/boot/status-monitor/status-overview'
import _ from 'lodash'
import moment from 'moment'
export default {
  name: 'stop-rate',
  components: {
    contentBox
  },
  data () {
    return {
      chart: null,
      workingTime: null,
      loading: false,
      workshop: null,
      stopData: []
    }
  },
  props: {
    workshopList: {
      type: Array,
      default: () => []
    }
  },
  mounted () {
    addListener(this.$refs.chart, this.$utils.debounce(() => {
      if (this.$route.name !== 'home') {
        return
      }
      if (this.chart === null) {
        this.chart = echarts.init(this.$refs.chart)
      } else {
        this.chart.resize()
        this.setOption()
      }
    }, 100))
    addListener(this.$refs.workingTime, this.$utils.debounce(() => {
      if (this.$route.name !== 'home') {
        return
      }
      if (this.workingTime === null) {
        this.workingTime = echarts.init(this.$refs.workingTime)
      } else {
        this.workingTime.resize()
        this.setworkingChartOption()
      }
    }, 100))
  },
  methods: {
    changeWorkshop (selId = null) {
      this.workshop = selId
      this.getShiftsDate()
    },
    // 获取当前班制日期
    getShiftsDate () {
      this.loading = true
      getShiftsDate(this.workshop).then(res => {
        if (res) {
          this.getShifts(res)
        } else {
          this.setOption([])
          this.setworkingChartOption([])
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取班制
    getShifts (date) {
      getShifts(this.workshop).then(res => {
        if (res.data.length) {
          const list = res.data.map(item => {
            return this.getDateTime(item, date)
          })
          console.log(list, '111111')
          const start = _.head(list).start
          const end = _.last(list).end
          console.log(`当日班制开始：${start},当日班制结束：${end}`)
          if (start && end) {
            // 有班制时间请求当班数据
            this.getStopChart({
              start,
              end,
              shiftDate: date
            })
          } else {
            this.loading = false
          }
        } else {
          this.loading = false
        }
      }).catch(() => {
        this.setOption([])
        this.setworkingChartOption([])
        this.loading = false
      })
    },
    // 根据时分获取日期时间
    getDateTime (shift = _.cloneDeep(this.shifts), date) {
      let dateObj = {}
      if (date) {
        const dateArr = _.split(date, '-')
        dateObj = {
          year: dateArr[0],
          month: dateArr[1] - 1, // moment月份需-1
          date: dateArr[2]
        }
      }
      let startArr = _.split(shift.startTime, ':')
      let startDateTime = moment().set({ ...dateObj, hours: Number(startArr[0]), minutes: Number(startArr[1]), seconds: 0 })

      let endArr = _.split(shift.endTime, ':', 2)
      let endDateTime = moment().set({ ...dateObj, hours: Number(endArr[0]), minutes: Number(endArr[1]), seconds: 0 })

      shift.isStartTimeOnNextDay && startDateTime.add(1, 'd')
      shift.isEndTimeOnNextDay && endDateTime.add(1, 'd')

      const params = {
        start: startDateTime.format('YYYY-MM-DDTHH:mm:ss'),
        end: endDateTime.format('YYYY-MM-DDTHH:mm:ss')
      }
      return params
    },
    // 获取图表数据
    getStopChart (time) {
      this.loading = true
      let params = {
        ...time,
        workshopId: this.workshop
      }
      getStopChart(params).then(res => {
        let stopData = []
        if (res.length) {
          stopData = res.map(item => {
            const runningTime = this.$utils.label(item.runningTime, 0)
            return {
              name: this.$utils.label(item.name),
              value: this.$utils.label(item.value, 0),
              runningTime: runningTime,
              percent: runningTime ? Number(this.$utils.label(item.value, 0) / runningTime * 100).toFixed(2) : 0.00
            }
          })
        }
        this.stopData = stopData
        this.setOption(this.stopData)
        this.setworkingChartOption(this.stopData)
      }).finally(() => {
        this.loading = false
      })
    },
    setOption (data = this.stopData) {
      if (this.chart === null) {
        this.chart = echarts.init(this.$refs.chart)
      }
      this.$nextTick(() => {
        const option = chart.getRateBar(data, ['#44D8C6', '#5F77FD'], this.$refs.chart)
        this.chart.setOption(option)
      })
    },
    setworkingChartOption (data = this.stopData) {
      if (this.workingTime === null) {
        this.workingTime = echarts.init(this.$refs.workingTime)
      }
      const stopTime = _.sumBy(data, 'value')
      const workingTime = data.length ? data[0].runningTime - stopTime : 0
      const color = ['#18D77F', '#FF8559']
      const seriesData = [
        { name: '加工占比', value: workingTime },
        { name: '停机占比', value: stopTime }]
      this.$nextTick(() => {
        const option = chart.getWorkingChart(color, seriesData, this.$refs.workingTime)
        this.workingTime.setOption(option)
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.form-inline{
  padding 0 !important
}
>>>.multipe-select{
  margin 0 !important
}
.text-grey{
  color #666666
}
</style>
